package com.ivory.valley.controller;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ivory.valley.common.IvoryValley;
import com.ivory.valley.common.Resp;
import com.ivory.valley.service.UserService;

@RestController
@RequestMapping("/signature")
public class SignatureController {
	/**
	 * 服务器配置接口
	 * @param request
	 * @param response
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 */
	
	@RequestMapping(value="/signature.dx",method=RequestMethod.GET)
	public void signature(HttpServletRequest request,HttpServletResponse response,
			String signature,String timestamp,String nonce,String echostr){
		String token = "ivory_valley2017";
		response.resetBuffer();
		String[] strs=new String[] {token,timestamp,nonce};  
	    Arrays.sort(strs);  
	    StringBuffer content=new StringBuffer();  
	    for (int i = 0; i < strs.length; i++) {  
	        content.append(strs[i]);  
	    }
	    MessageDigest md = null;
	    String result = null;
		try {
			//sha加密
			md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(content.toString().getBytes());
			result = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}    
		 // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		try {
			response.getWriter().print(result != null&&result.equals(signature.toUpperCase()) ? echostr  : "");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 字节数组转成16进制字符串
	 * @param digest
	 * @return
	 */
	private String byteToStr(byte[] digest) {
		String strDigest = "";
        for (int i = 0; i < digest.length; i++) {
            strDigest += byteToHexStr(digest[i]);
         }
		   return strDigest;
	}
	/**
	 * 字节转成16进制字符串
	 * @param b
	 * @return
	 */
	private static String byteToHexStr(byte b) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				                 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(b >>> 4) & 0X0F];
        tempArr[1] = Digit[b & 0X0F];

        String s = new String(tempArr);
        return s;
	}
}
